<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('proPlan:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="单据编号">
                <a-input v-model.trim="queryParam.code" allow-clear placeholder="请输入单据编号"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="备注">
                <a-input v-model="queryParam.remarks" allow-clear placeholder="请输入备注"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="allNull();$refs.table.refresh(true)">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :rowKey="(record) => record.id"
        :rowSelection="options.rowSelection"
        :components="this.comp"
        :scroll="{ x: 1200 }"
        bordered
      >
        <template class="table-operator" slot="operator" v-if="hasPerm('proPlan:add')" >
          <a-button type="primary" v-if="hasPerm('proPlan:add')" icon="plus" @click="$refs.addForm.add()">新增生产计划</a-button>
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('proPlan:delete')" @click="batchDelete"><a-icon type="delete"/>批量删除</a-button>
          <x-down
            v-if="hasPerm('proPlan:export')"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <template slot="docProgress" slot-scope="text">
          <div style="width: 170px">
            <a-progress :percent="text" size="small"/>
          </div>
        </template>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('proPlan:detail')" @click="$refs.detailForm.open(record)">查看</a>
          <a-divider type="vertical" v-if="hasPerm('proType:edit') & hasPerm('proType:delete')"/>
          <a v-if="hasPerm('proPlan:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('proPlan:edit') & hasPerm('proPlan:delete')"/>
          <a-popconfirm v-if="hasPerm('proPlan:delete')" placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <add-form ref="addForm" @ok="handleOk" />
      <edit-form ref="editForm" @ok="handleOk" />
      <detail-form ref="detailForm" @ok="handleOk" />
    </a-card>
  </div>
</template>
<script>
import { STable, XDown } from '@/components'
import { proPlanPage, proPlanDelete, proPlanExport } from '@/api/modular/main/proplan/proPlanManage'
import addForm from './addForm.vue'
import editForm from './editForm.vue'
import detailForm from './detailForm.vue'
import '@/mixins/drag/drag.css'
import dragMixin from '@/mixins/drag/index'
import { sysUserDetail } from '@/api/modular/system/userManage'
export default {
  components: {
    STable,
    addForm,
    editForm,
    detailForm,
    XDown
  },
  mixins: [ dragMixin ],
  data () {
    return {
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '单据编号',
          align: 'center',
          dataIndex: 'code',
          width: 200,
          ellipsis: true
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUserName',
          width: 200,
          ellipsis: true
        },
        {
          title: '工单数',
          align: 'center',
          dataIndex: 'workOrderList.length',
          width: 100,
          ellipsis: true
        },
        {
          title: '已结束工单',
          align: 'center',
          dataIndex: 'endWorkerorderNum',
          width: 100,
          ellipsis: true
        },
        {
          title: '单据进度',
          align: 'center',
          dataIndex: 'docProgress',
          width: 200,
          scopedSlots: { customRender: 'docProgress' }
          // ellipsis: true
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 200,
          ellipsis: true
        },

        {
          title: '修改人',
          align: 'center',
          dataIndex: 'updateUserName',
          width: 200,
          ellipsis: true
        },
        {
          title: '修改时间',
          align: 'center',
          dataIndex: 'updateTime',
          width: 200,
          ellipsis: true
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remarks',
          width: 200,
          ellipsis: true
        }
      ],
      tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return proPlanPage(Object.assign(parameter, this.queryParam)).then((res) => {
          res.data.rows.forEach(item => {
            // 为取回数据添加新属性
            // this.getDocumentProgress(item.workOrderList)
            item.docProgress = this.getDocumentProgress(item.workOrderList)
          })
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      username: ''
    }
  },
  created () {
    if (this.hasPerm('proPlan:edit') || this.hasPerm('proPlan:delete')) {
      this.columns.push({
        title: '操作',
        width: 350,
        align: 'center',
        fixed: 'right',
        // drag需注释掉
        // dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    async userName(userid) {
      this.username = await sysUserDetail({ id: userid }).then(res => res.data.name)
      return this.username
    },
    // 重置
    allNull() {
      this.queryParam = {}
    },
    // 控制收起
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    /**
     * 计算单据进度已完成百分比
     */
    getDocumentProgress(val) {
      let total = 0
      let num = 0
      val.forEach(item => {
        // 状态为未开始和已取消算0
        if (item.status === -1 || item.status === -2) {
          total += 0
        }
        if (item.status === 1) { // 状态为已结束算1
          total += 100
        }
        if (item.status === 0) { // 状态为开始计算其中的平均值
          item.progressRateList.forEach(childItem => {
            num += (childItem <= item.plaNum ? childItem : item.plaNum)
          })
          total += num / item.progressRateList.length * 100
        }
      })
      return parseInt(total / val.length)
    },
    /**
     * 单个删除
     */
    singleDelete (record) {
      const param = [{ 'id': record.id }]
      this.proPlanDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete () {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { 'id': d }
      })
      this.proPlanDelete(paramIds)
    },
    proPlanDelete (record) {
      proPlanDelete(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.clearRefreshSelected()
        } else {
          this.$message.error('删除失败') // + res.message
        }
      })
    },
    /**
     * 批量导出
     */
    batchExport () {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { 'id': d }
      })
      proPlanExport(paramIds).then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.progress-wrap{
  display: flex;
  align-items: center;
}
.total-progress {
  width: 150px;
  height: 8px;
  background-color: rgba(0, 0, 0, 0.04);
  border-radius: 4px;
}
.progress {
  height: 100%;
  background-color: #1890FF;
  border-radius: 4px;
}
.progress-num{
  margin-left: 5px;
}
</style>
